#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "../include/platform.h"
#include "../include/common.h"
#include "../include/threadpool.h"

#include "../include/server.h"

ThreadPool pool;
int srv; // global server socket (used by signal handler)

// 定义默认端口变量
int SERVER_PORT = DEFAULT_SERVER_PORT;

int set_server_port(int port) {
	if (port <= 0 || port > 65535) return -1;
	SERVER_PORT = port;
	return 0;
}

void sigint_handler(int sig) {
	platform_close();
	close_thread_pool(&pool);
	close(srv);
	exit(0);
}

int main(int argc, char *argv[]) {
	// 可选地从命令行读取端口号： ./server [port]
	if (argc > 1) {
		int p = atoi(argv[1]);
		if (set_server_port(p) != 0) {
			fprintf(stderr, "invalid port: %s\n", argv[1]);
			return 1;
		}
	}

	platform_init();
	init_thread_pool(&pool);

	srv = socket(AF_INET, SOCK_STREAM, 0);
	if (srv < 0) { perror("socket"); return 1; }

	int opt = 1;
	setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = INADDR_ANY;
	addr.sin_port = htons(SERVER_PORT);

	if (bind(srv, (struct sockaddr*)&addr, sizeof(addr)) < 0) { perror("bind"); return 1; }
	if (listen(srv, 5) < 0) { perror("listen"); return 1; }

	printf("server listening on %d\n", SERVER_PORT);

	while (1) {
		struct sockaddr_in cliaddr; socklen_t len = sizeof(cliaddr);
		int fd = accept(srv, (struct sockaddr*)&cliaddr, &len);
		if (fd < 0) { perror("accept"); continue; }
		printf("client get connection from %d\n", (int)cliaddr.sin_addr.s_addr);
		if (add_fd(&pool, fd) != 0) {
			perror("thread pool is full\n");
			continue;
		} else {
			fflush(stdout);
		}
	}
}
